<template>
  <view class="refund-page">
    <!-- 商品信息 -->
    <view class="order-info" v-if="orderInfo && orderInfo.id">
      <view class="order-header">
        <text class="order-title">订单信息</text>
        <text class="order-number">订单号：{{ orderInfo.orderNumber }}</text>
      </view>
      <view class="goods-item">
        <image class="goods-image" :src="orderInfo.pic" mode="aspectFill"></image>
        <view class="goods-detail">
          <view class="goods-name">{{ orderInfo.prodName }}</view>
          <view class="goods-spec">{{ orderInfo.remark || '' }}</view>
          <view class="goods-price">
            <text class="price">￥{{ formatPrice(orderInfo.price) }}</text>
            <text class="num">x{{ orderInfo.num }}</text>
          </view>
        </view>
      </view>
      <view class="order-amount">
        <text class="label">实付金额：</text>
        <text class="amount">￥{{ formatPrice(orderInfo.actualTotal) }}</text>
      </view>
    </view>

    <!-- 退款申请信息 -->
    <view class="refund-info" v-if="serviceInfo && serviceInfo.id">
      <view class="info-header">
        <text class="info-title">退款申请</text>
        <text class="apply-time">申请时间：{{ serviceInfo.createTime || '' }}</text>
      </view>
      
      <view class="info-item">
        <text class="item-label">退款类型</text>
        <text class="item-value">{{ getApplyTypeText(serviceInfo.applyType) }}</text>
      </view>
      
      <view class="info-item">
        <text class="item-label">退款金额</text>
        <text class="item-value refund-amount">￥{{ formatPrice(serviceInfo.refundAmount) }}</text>
      </view>
      
      <view class="info-item">
        <text class="item-label">退货数量</text>
        <text class="item-value">{{ serviceInfo.goodsNum || 0 }}件</text>
      </view>
      
      <view class="info-item">
        <text class="item-label">退款原因</text>
        <text class="item-value reason">{{ serviceInfo.buyerMsg || '无' }}</text>
      </view>
      
      <view class="info-item" v-if="photoList.length > 0">
        <text class="item-label">退款凭证</text>
        <view class="photo-list">
          <image 
            v-for="(photo, index) in photoList" 
            :key="index"
            :src="photo" 
            mode="aspectFill" 
            class="photo-item"
            @click="previewImage(photo)"
          ></image>
        </view>
      </view>
    </view>

    <!-- 审核表单 -->
    <view class="review-form" v-if="serviceInfo && serviceInfo.id">
      <view class="form-header">
        <text class="form-title">审核处理</text>
      </view>
      
      <u--form ref="formRef" :model="formData" :rules="rules" labelWidth="120">
        
        <!-- 审核结果 -->
        <u-form-item label="审核结果" prop="status" required>
          <u-radio-group v-model="formData.status" size="28">
            <u-radio :name="2" label="同意" activeColor="#19be6b" icon-size="28" label-size="28"></u-radio>
            <u-radio :name="3" label="拒绝" activeColor="#fa3534" icon-size="28" label-size="28"></u-radio>
          </u-radio-group>
        </u-form-item>

        <!-- 卖家备注 -->
        <u-form-item label="备注说明" prop="sellerMsg" :required="formData.status === 3">
          <u--textarea 
            v-model="formData.sellerMsg" 
            :placeholder="formData.status === 3 ? '请填写拒绝原因' : '备注信息（选填）'"
            border="none"
            count
            maxlength="200"
            autoHeight
            height="120"
          ></u--textarea>
        </u-form-item>
        
      </u--form>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-container" v-if="serviceInfo && serviceInfo.id">
      <u-button 
        type="primary" 
        size="large" 
        @click="submitReview"
        :loading="submitting"
        :disabled="submitting"
      >
        {{ submitting ? '提交中...' : '提交审核' }}
      </u-button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      orderId: "",//订单id
      orderInfo: {},//订单信息
      serviceInfo: {},//售后信息
      submitting: false,
      formData: {
        status: 2, // 处理状态: 2为同意,3为不同意
        sellerMsg: '', // 卖家备注
      },
      rules: {
        status: [{ required: true, message: '请选择审核结果' }],
        sellerMsg: [
          { validator: this.validateSellerMsg, message: '拒绝时必须填写原因' }
        ]
      }
    }
  },
  onLoad(opt) {
    if (opt && opt.id) {
      this.orderId = opt.id
      this._getOrderDetail(opt.id)
      this._getServiceInfo(opt.id)
    }
  },
  computed: {
    // 解析图片列表
    photoList() {
      if (this.serviceInfo.photoFiles) {
        return this.serviceInfo.photoFiles.split(',').filter(url => url.trim())
      }
      return []
    }
  },
  methods: {
    // 根据id查询订单详情
    _getOrderDetail(id) {
      let params = {id}
      this.$api.getOrderDetail(params).then(res => {
        if (res.success) {
          this.orderInfo = res.result
        }
      })
    },
    
    // 格式化价格
    formatPrice(v) {
      const n = Number(v || 0)
      return n.toFixed(2)
    },
    
    // 查询售后信息
    _getServiceInfo(id) {
      let params = {orderId: id}
      this.$api.getMssdOrderRefundList(params).then(res => {
        if (res.success) {
          if (res.result.records.length > 0) {
            this.serviceInfo = res.result.records[0] || {}
          }
        }
      })
    },

    // 获取申请类型文本
    getApplyTypeText(type) {
      const typeMap = {
        1: '仅退款',
        2: '退款退货'
      }
      return typeMap[type] || '未知'
    },

    // 预览图片
    previewImage(url) {
      uni.previewImage({
        urls: this.photoList,
        current: url
      })
    },

    // 验证卖家备注
    validateSellerMsg(rule, value, callback) {
      if (this.formData.status === 3 && (!value || value.trim() === '')) {
        callback(false)
      } else {
        callback(true)
      }
    },

    // 提交审核
    async submitReview() {
      try {
        const valid = await this.$refs.formRef.validate()
        if (!valid) return

        this.submitting = true

        const params = {
          id: this.serviceInfo.id,
          status: this.formData.status,
          sellerMsg: this.formData.sellerMsg
        }

        const res = await this.$api.sellerRefundReview(params)
        
        if (res.success) {
          const statusText = this.formData.status === 2 ? '同意' : '拒绝'
          uni.showToast({
            title: `审核${statusText}成功`,
            icon: 'success'
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: res.message || '审核失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('提交审核失败:', error)
        uni.showToast({
          title: '提交失败，请重试',
          icon: 'none'
        })
      } finally {
        this.submitting = false
      }
    }
  },
}
</script>

<style lang="scss" scoped>
.refund-page {
  background: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.order-info {
  background: #fff;
  margin: 20rpx 0;

  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 32rpx 20rpx;
    border-bottom: 1rpx solid #f0f2f5;

    .order-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #1d2129;
    }

    .order-number {
      font-size: 24rpx;
      color: #86909c;
    }
  }

  .goods-item {
    display: flex;
    padding: 20rpx 32rpx;

    .goods-image {
      width: 120rpx;
      height: 120rpx;
      border-radius: 12rpx;
      margin-right: 20rpx;
    }

    .goods-detail {
      flex: 1;

      .goods-name {
        font-size: 28rpx;
        color: #1d2129;
        line-height: 1.4;
        margin-bottom: 8rpx;
      }

      .goods-spec {
        font-size: 24rpx;
        color: #86909c;
        margin-bottom: 12rpx;
      }

      .goods-price {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .price {
          font-size: 28rpx;
          color: #ff3131;
          font-weight: 600;
        }

        .num {
          font-size: 24rpx;
          color: #86909c;
        }
      }
    }
  }

  .order-amount {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 20rpx 32rpx;
    border-top: 1rpx solid #f0f2f5;

    .label {
      font-size: 28rpx;
      color: #4e5969;
    }

    .amount {
      font-size: 32rpx;
      color: #ff3131;
      font-weight: 600;
      margin-left: 10rpx;
    }
  }
}

.refund-info {
  background: #fff;
  margin: 20rpx 0;
  
  .info-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 32rpx 20rpx;
    border-bottom: 1rpx solid #f0f2f5;
    
    .info-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #1d2129;
    }
    
    .apply-time {
      font-size: 24rpx;
      color: #86909c;
    }
  }
  
  .info-item {
    display: flex;
    align-items: flex-start;
    padding: 24rpx 32rpx;
    border-bottom: 1rpx solid #f8f9fa;
    
    &:last-child {
      border-bottom: none;
    }
    
    .item-label {
      width: 160rpx;
      font-size: 28rpx;
      color: #4e5969;
      flex-shrink: 0;
    }
    
    .item-value {
      flex: 1;
      font-size: 28rpx;
      color: #1d2129;
      
      &.refund-amount {
        color: #ff3131;
        font-weight: 600;
        font-size: 32rpx;
      }
      
      &.reason {
        line-height: 1.5;
      }
    }
    
    .photo-list {
      display: flex;
      flex-wrap: wrap;
      gap: 12rpx;
      
      .photo-item {
        width: 120rpx;
        height: 120rpx;
        border-radius: 8rpx;
        border: 1rpx solid #e5e6eb;
      }
    }
  }
}

.review-form {
  background: #fff;
  margin: 20rpx 0;
  
  .form-header {
    padding: 30rpx 32rpx 20rpx;
    border-bottom: 1rpx solid #f0f2f5;
    
    .form-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #1d2129;
    }
  }
}

.submit-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx 32rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  border-top: 1rpx solid #f0f2f5;
  box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.08);
}

// uView组件样式覆盖
::v-deep .u-form-item {
  padding: 24rpx 32rpx !important;
  
  .u-form-item__body__left__content__label {
    font-size: 28rpx !important;
    color: #1d2129 !important;
    font-weight: 500 !important;
  }
}

::v-deep .u-radio-group {
  display: flex;
  gap: 40rpx;
}

::v-deep .u-radio {
  margin-right: 0 !important;
}
</style>
